//
//  XGTopicTableViewController
//  BSBuDeJie
//
//  Created by monkey on 2018/12/18.
//  Copyright © 2018 itcast. All rights reserved.
//

#import <MJRefresh/MJRefresh.h>
#import <SDWebImage/SDImageCache.h>

#import "XGTopicTableViewController.h"

#import "XGDataManager.h"

#import "XGTopicModel.h"

#import "XGVideoTopicTableViewCell.h"
#import "XGVoiceTopicTableViewCell.h"
#import "XGPictureTopicTableViewCell.h"
#import "XGWordTopicTableViewCell.h"

/// 视频cell重用标识符
static NSString *const kVideoTopicTableViewCellReuseIdentifier = @"XGVideoTopicTableViewCell";
/// 声音cell重用标识符
static NSString *const kVoiceTopicTableViewCellReuseIdentifier = @"XGVoiceTopicTableViewCell";
/// 图片cell重用标识符
static NSString *const kPictureTopicTableViewCellReuseIdentifier = @"XGPictureTopicTableViewCell";
/// 段子cell重用标识符
static NSString *const kWordTopicTableViewCellReuseIdentifier = @"XGWordTopicTableViewCell";

@interface XGTopicTableViewController ()

/// 数据
@property (nonatomic,strong) NSMutableArray<XGTopicModel *> *dataArrayM;

/// 下拉刷新提示文本
@property (nonatomic,strong) UILabel *pullRefreshTipLabel;

@end

@implementation XGTopicTableViewController

#pragma mark - 控制器生命周期方法

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // 设置刷新提示控件
    [self setUpRefreshTipLabel];
    // 设置tableView
    [self setUpTableView];
    // 加载数据
    [self loadNewData];
}

#pragma mark - 公开方法

- (XGTopicType)topicType
{
    return XGTopicTypeAll;
}

#pragma mark - 内部其他私有方法

// 设置刷新提示控件
- (void)setUpRefreshTipLabel
{
    [self.navigationController.navigationBar addSubview:self.pullRefreshTipLabel];
    // 将控件放置到最后面
    [self.navigationController.navigationBar sendSubviewToBack:self.pullRefreshTipLabel];
    CGRect frame = self.navigationController.navigationBar.bounds;
    self.pullRefreshTipLabel.frame = CGRectOffset(frame, 0, -frame.size.height * 2);
}

// 设置tableView
- (void)setUpTableView
{
    // 设置内容边距
    self.tableView.contentInset = UIEdgeInsetsMake(kStatusBarHeight + kNavigationBarHeight + kHomeTitleViewHeight, 0, kTabBarHeight, 0);
    // 设置滚动条边距
    self.tableView.scrollIndicatorInsets = self.tableView.contentInset;
    
    // 设置预估行高
    self.tableView.estimatedRowHeight = 300.f;
    
    // 设置分割线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    // 取消scrollView默认64偏移
    self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    
    // 设置上拉刷新和下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    self.tableView.mj_header.hidden = YES;
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    // 注册视频cell
    [self.tableView registerClass:[XGVideoTopicTableViewCell class] forCellReuseIdentifier:kVideoTopicTableViewCellReuseIdentifier];
    // 注册声音cell
    [self.tableView registerClass:[XGVoiceTopicTableViewCell class] forCellReuseIdentifier:kVoiceTopicTableViewCellReuseIdentifier];
    // 注册图片cell
    [self.tableView registerClass:[XGPictureTopicTableViewCell class] forCellReuseIdentifier:kPictureTopicTableViewCellReuseIdentifier];
    // 注册段子cell
    [self.tableView registerClass:[XGWordTopicTableViewCell class] forCellReuseIdentifier:kWordTopicTableViewCellReuseIdentifier];
}

// 加载帖子数据
- (void)loadDataWithMaxTime:(NSInteger)maxTime minTime:(NSInteger)minTime
{
    [XGDataManager loadTopicWithType:[self topicType] maxTime:maxTime minTime:minTime completion:^(NSArray<XGTopicModel *> * _Nullable dataArray, NSError * _Nullable error) {
        if (self.tableView.mj_header.isRefreshing) {
            [self.tableView.mj_header endRefreshing];
            self.tableView.mj_header.hidden = YES;
        } else if (self.tableView.mj_footer.isRefreshing) {
            [self.tableView.mj_footer endRefreshing];
        }
        
        if (error) {
            DEBUG_Log(@"加载全部帖子数据失败");
            return;
        }
        
        if (minTime != 0) {
            // 展示刷新到多少条数据
            [self showRefreshCountText:dataArray.count];
            // 如果是下拉刷新 将新数据追加到前面
            if (dataArray.count > 0) {
                NSMutableArray<XGTopicModel *> *tmpArrayM = [NSMutableArray arrayWithArray:dataArray];
                [tmpArrayM addObjectsFromArray:self.dataArrayM];
                self.dataArrayM = tmpArrayM;
                [self.tableView reloadData];
            }
        } else {
            // 如果是上拉刷新 将新数据追加到后面
            [self.dataArrayM addObjectsFromArray:dataArray];
            [self.tableView reloadData];
        }
    }];
}

// 加载最新帖子数据
- (void)loadNewData
{
    if (self.tableView.mj_footer.isRefreshing) {
        return;
    } else {
        [self loadDataWithMaxTime:0 minTime:[self.dataArrayM.firstObject timeId]];
    }
}

// 加载更多帖子数据
- (void)loadMoreData
{
    if (self.tableView.mj_header.isRefreshing) {
        return;
    } else {
        [self loadDataWithMaxTime:[self.dataArrayM.lastObject timeId] minTime:0];
    }
}

// 展示刷新数据提示
- (void)showRefreshCountText:(NSInteger)count
{
    self.pullRefreshTipLabel.text = [NSString stringWithFormat:@"共刷新到%zd条新数据",count];
    
    // 动画展示
    [UIView animateWithDuration:2 animations:^{
        self.pullRefreshTipLabel.frame = CGRectOffset(self.pullRefreshTipLabel.bounds, 0, 2 * self.pullRefreshTipLabel.height);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:2 animations:^{
            self.pullRefreshTipLabel.frame = CGRectOffset(self.pullRefreshTipLabel.bounds, 0, -2 * self.pullRefreshTipLabel.height);
        }];
    }];
}

- (NSString *)reuseIdentifierWithTopicModel:(XGTopicModel *)topicModel
{
    if (topicModel.type == XGTopicTypeVideo) {
        return kVideoTopicTableViewCellReuseIdentifier;
    } else if (topicModel.type == XGTopicTypeVoice) {
        return kVoiceTopicTableViewCellReuseIdentifier;
    } else if (topicModel.type == XGTopicTypePicture) {
        return kPictureTopicTableViewCellReuseIdentifier;
    } else {
        return kWordTopicTableViewCellReuseIdentifier;
    }
}

#pragma mark - UITableViewDataSource & Delegate

// 多少组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

// 多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    self.tableView.mj_footer.hidden = self.dataArrayM.count == 0;
    return self.dataArrayM.count;
}

// 每行的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    XGTopicModel *topicModel = self.dataArrayM[indexPath.row];
    XGBaseTopicTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[self reuseIdentifierWithTopicModel:topicModel]];
    cell.topicModel = topicModel;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.dataArrayM[indexPath.row].rowHeight;
}

// scrollView滚动的时候调用
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    // 向下滚动时显示下拉刷新 向上滚动 隐藏下拉刷新控件
    if (scrollView.contentOffset.y < -scrollView.contentInset.top) {
        self.tableView.mj_header.hidden = NO;
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [[SDImageCache sharedImageCache] clearMemory];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (!self.tableView.mj_header.isRefreshing) {
        self.tableView.mj_header.hidden = YES;
    }
}

#pragma mark - 懒加载

- (NSMutableArray<XGTopicModel *> *)dataArrayM
{
    if (_dataArrayM == nil) {
        _dataArrayM = [NSMutableArray array];
    }
    
    return _dataArrayM;
}

- (UILabel *)pullRefreshTipLabel
{
    if (_pullRefreshTipLabel == nil) {
        _pullRefreshTipLabel = [UILabel labelWithText:@"刷新到5条最新数据" textColor:[UIColor whiteColor] font:15 textAlignment:NSTextAlignmentCenter];
        _pullRefreshTipLabel.backgroundColor = [UIColor orangeColor];
    }
    
    return _pullRefreshTipLabel;
}

@end
